<template>
  <!-- 宠物档案 -->
  <view class="components">
    <view v-for="(item, index) in petList" :key="index">
      <view class="mainBox" v-if="item.show">
        <!-- 基本信息 -->
        <view class="basicInfo">
          <view class="petInfoBox lineBox">
            <view class="leftPetImg">
              <image
                :src="item?.mediaList[0] || '/static/my/pet.png'"
                mode="aspectFit"
              ></image>
            </view>
            <view class="rightBox">
              <view class="form-item lineBox">
                <text class="title">基本信息</text>
                <image
                  class="editTextImg"
                  @click="editPetInfo(item)"
                  src="/static/my/editText.png"
                  mode="aspectFit"
                ></image>
              </view>
              <view class="form-item lineBox">
                <text class="form-label">姓名：</text>
                <text class="form-value">{{ item.name }}</text>
              </view>
              <view class="form-item lineBox">
                <text class="form-label">性别：</text>
                <text class="form-value">{{ item.gender }}</text>
              </view>
              <view class="form-item lineBox">
                <text class="form-label">年龄：</text>
                <view class="from-right" style="text-align: right">
                  <view class="form-value" style="text-align: right">
                    {{ item.age }}岁
                  </view>
                  <view class="form-label" style="text-align: right"
                    >约等于人的{{ item.aboutYearsOld }}岁</view
                  >
                </view>
              </view>
              <view class="form-item lineBox">
                <text class="form-label">出生日期：</text>
                <text class="form-value">{{ item.birthDate }}</text>
              </view>
              <view class="form-item lineBox">
                <text class="form-label">品种：</text>
                <text class="form-value">{{ item.breed }}</text>
              </view>
            </view>
          </view>
          <view class="form-bottom lineBox">
            <view class="form-item">
              <text class="form-label">最新身价：</text>
              <text class="form-value">￥{{ item.latestValue }}</text>
            </view>
            <view class="form-item">
              <text class="form-label">已陪伴：</text>
              <text class="form-value">{{ item.accompanyDays }}天</text>
            </view>
          </view>
        </view>

        <!-- 宠物日记 -->
        <view class="diaryBox">
          <view class="title1">
            <view class="">宠物日记</view>
            <view class="" @click="postDiary(item)">发日记</view>
          </view>
          <view class="shopListMain">
            <view
              class="leftList"
              v-for="(fitem, findex) in noteList"
              :key="findex"
            >
              <view v-for="(item, index) in fitem" :key="index" class="card">
                <!-- image 是否是图片 1是图片 2不是图片， -->
                <view
                  v-if="item.noteType === 1"
                  class="image-container"
                  @click="goDetail(item)"
                >
                  <image
                    :src="item.firstPicture"
                    class="image"
                    mode="widthFix"
                  ></image>
                  <text class="DirartText">{{ item.noteTitle }}</text>
                </view>
                <view
                  v-else
                  class="video-container"
                  :style="{ height: item.height + 'rpx' }"
                  @click="goDetail(item)"
                >
                  <image :src="item.firstPicture" class="image"></image>
                  <image
                    class="bofangImg"
                    src="/static/my/bofangIcon.png"
                    mode=""
                  ></image>
                  <text class="DirartText">{{ item.noteTitle }}</text>
                </view>
              </view>
              <view v-if="findex == 1">
                <view class="moreText" v-if="hasMore" @click="loadMore">
                  查看更多 >
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 身体数据概况 -->
        <view class="bodyData">
          <view class="title1"> 身体数据概况 </view>
          <view class="bodyData-box">
            <view class="form-item w300 lineBox">
              <text class="form-label">体重：</text>
              <text class="form-value">{{ item.weight }}KG</text>
            </view>
            <view class="form-item w300 lineBox">
              <text class="form-label">腿长：</text>
              <text class="form-value">{{ item.legLength }}CM</text>
            </view>
            <view class="form-item w300 lineBox">
              <text class="form-label">头围：</text>
              <text class="form-value">{{ item.headCircumference }}CM</text>
            </view>
            <view class="form-item w300 lineBox">
              <text class="form-label">尾长：</text>
              <text class="form-value">{{ item.tailLength }}CM</text>
            </view>
            <view class="form-item w300 lineBox">
              <text class="form-label">腰围：</text>
              <text class="form-value">{{ item.waistCircumference }}CM</text>
            </view>
            <view class="form-item w300 lineBox">
              <text class="form-label">爪子颜色：</text>
              <text class="form-value">{{ item.pawColor }}</text>
            </view>
            <view class="form-item w300 lineBox">
              <text class="form-label">颈围：</text>
              <text class="form-value">{{ item.neckCircumference }}CM</text>
            </view>
            <view class="form-item w300 lineBox">
              <text class="form-label">眼睛颜色：</text>
              <text class="form-value">{{ item.eyeColor }}</text>
            </view>
            <view class="form-item w300 lineBox">
              <text class="form-label">身长：</text>
              <text class="form-value">{{ item.bodyLength }}CM</text>
            </view>
          </view>
        </view>
        <!-- 性格行为习惯展示 -->
        <view class="natureBox">
          <view class="title1"> 性格行为习惯展示 </view>
          <view class="natureText">{{ item.personalityHabit }}</view>
        </view>
        <!-- 病历 -->
        <view class="medicalRecord">
          <view class="title"> 病历 </view>
          <view class="moreText" @click="moreMedicalRecord(item)">
            点击显示>
          </view>
        </view>
      </view>

      <view class="mainBoxHide" v-else @click="showPet(item)">{{
        item.name
      }}</view>
    </view>
    <view class="addBtn" @click="editPetInfo()"
      >+ 宠物 {{ petList.length + 1 }}</view
    >
  </view>
</template>

<script>
import { timestampToTime } from "@/utils/filters.js";
import shopList from "./shopList.vue";
import commonMixin from "@/mixin/commonMinxin";

export default {
  mixins: [commonMixin],
  components: {
    shopList,
  },
  data() {
    return {
      petList: [],
      noteList: [[], []],
      columnHeights: [0, 0], // 新增：记录每列累计高度
      page: 1, // 添加页码变量
      hasMore: true, // 添加是否有更多数据标志
      apiLoadingStatus: false, // 添加加载状态标志
    };
  },
  created() {
    this.getPet();
    // We'll load notes after pets are fetched
  },
  methods: {
    getPet() {
      console.log(uni.getStorageSync("userId"));
      uni.app.post(
        "/pet/info/getInfos",
        { userId: uni.getStorageSync("userId"), offset: 1, limit: 10 },
        "json",
        "",
        (res) => {
          this.petList = res.data.records;

          // this.petList.forEach((item, idx) => { item.show = idx === 0; });
          this.petList.forEach((item, idx) => {
            item.show = idx === 0;
            item.birthDate = timestampToTime(item.birthDate);
          });

          // 获取宠物列表后，加载第一个宠物的日记
          this.getNotes();
        },
      );
    },
    getNotes(isReload) {
      const that = this;
      if (isReload) {
        this.page = 1;
        this.noteList = [[], []];
        this.columnHeights = [0, 0];
      }
      this.apiLoadingStatus = true;

      // 获取当前显示的宠物ID
      const selectedPet = this.petList.find((pet) => pet.show);
      const petId = selectedPet ? selectedPet.id : "";

      let params = {
        authorId: uni.getStorageSync("userId"),
        // followId: uni.getStorageSync("userId"),
        petId: Number(petId),
        noteCategory: 1,
        limit: 4,
        offset: this.page, // 使用当前页码作为偏移量
      };
      uni.app.post("/blog/note/getNotes", params, "", "", (res) => {
        this.apiLoadingStatus = false;
        if (res.code == 2000) {
          let notes = res.data.records || [];
          if (notes.length > 0) {
            for (var i = 0; i < notes.length; i++) {
              // 获取当前卡片高度，根据图片比例计算
              let itemHeight = 300; // 默认高度
              if (notes[i].firstPictureHeight && notes[i].firstPictureWidth) {
                // 计算宽高比，考虑宽度固定为列宽的一半
                const columnWidth = 330; // 假设列宽为屏幕宽度的一半(750/2 - 间距)
                const aspectRatio =
                  notes[i].firstPictureHeight / notes[i].firstPictureWidth;
                itemHeight = columnWidth * aspectRatio;
              }
              notes[i].height = itemHeight;

              // 找到当前高度最小的列
              let minIndex =
                that.columnHeights[0] <= that.columnHeights[1] ? 0 : 1;
              that.noteList[minIndex].push(notes[i]);
              that.columnHeights[minIndex] += itemHeight;
            }
            that.page++;
            that.hasMore = that.page <= res.data.pages;
          } else {
            that.hasMore = false;
          }
        }
      });
    },
    // 添加加载更多方法
    loadMore() {
      if (this.hasMore && !this.apiLoadingStatus) {
        // 获取当前显示的宠物ID
        const selectedPet = this.petList.find((pet) => pet.show);
        const petId = selectedPet ? selectedPet.id : "";

        uni.navigateTo({
          url: `/pages/petDiary/petDiary?petId=${petId}`,
        });
      }
    },
    showPet(item) {
      // 先全部设为 false
      this.petList.forEach((pet) => {
        pet.show = false;
      });
      // 当前 item 设为 true
      item.show = true;

      // 重置日记数据并重新加载当前宠物的日记
      this.page = 1;
      this.noteList = [[], []];
      this.columnHeights = [0, 0];
      this.getNotes(true);
    },
    goDetail(item) {
      console.log(item);

      let c = {
        hideNavBar: "1",
        hideTotalNavBar: "1",
        hideBottomSafeBar: "1",
        url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/notes/detail/detail?noteId=${item.noteId}&token=${uni.getStorageSync("token")}&userId=${uni.getStorageSync("userId")}`,
      };
      this.fn(c);
    },
    editPetInfo(item) {
      if (item) {
        let b = {
          hideNavBar: "0",
          hideTotalNavBar: "0",
          hideBottomSafeBar: "0",
          navtitle: "编辑宠物档案",
          url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/my/editPetProfile?petId=${item.id}&token=${uni.getStorageSync("token")}&userId=${uni.getStorageSync("userId")}`,
        };
        this.fn(b);
      } else {
        let a = {
          hideNavBar: "0",
          hideTotalNavBar: "0",
          hideBottomSafeBar: "0",
          navtitle: "新增宠物",
          url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/my/editPetProfile?token=${uni.getStorageSync("token")}&userId=${uni.getStorageSync("userId")}`,
        };
        this.fn(a);
      }
    },
    postDiary(item) {
      let w = { id: item.id };
      this.fn1(w);
    },
    moreMedicalRecord(item) {
      let data = {
        hideNavBar: "0",
        hideTotalNavBar: "0",
        hideBottomSafeBar: "0",
        navtitle: "宠物病历",
        url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/my/editPetMedicalRecord?petId=${item.id}&token=${uni.getStorageSync("token")}&userId=${uni.getStorageSync("userId")}`,
      };
      this.fn(data);
    },
    fn(data) {
      switch (uni.getSystemInfoSync().platform) {
        case "android":
          let d = JSON.stringify(data);
          console.log(d, "都是对的");
          window.AndroidBridge.pushNewWebVC(d);
          console.log("运行Android上");
          break;
        case "ios":
          window.webkit.messageHandlers.pushNewWebVC.postMessage(data);
          break;
        default:
          console.log("运行在开发者工具上");
          break;
      }
    },
    fn1(data) {
      switch (uni.getSystemInfoSync().platform) {
        case "android":
          let ddd = data;
          let d = JSON.stringify(ddd);
          console.log(d, "都是对的");
          window.AndroidBridge.petPublishEvent(d);
          console.log("运行Android上");
          break;
        case "ios":
          window.webkit.messageHandlers.petPublishEvent.postMessage(data);
          break;
        default:
          console.log("运行在开发者工具上");
          break;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.components {
  .lineBox {
    border-bottom: 2rpx solid #f8f8f8;
  }

  .form-item {
    display: flex;
    justify-content: space-between;
    padding: 15rpx 0;

    .form-label {
      font-weight: 500;
      font-size: 24rpx;
      color: #7f7f7f;
    }

    .form-value {
      font-weight: bold;
      font-size: 26rpx;
      color: #303030;
    }

    .from-right {
      flex: 1;
    }

    &:last-child {
      border-bottom: none;
    }
  }

  .form-header {
    padding: 0 0 15rpx;
  }

  .form-bottom {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 15rpx;
  }

  .mainBox {
    background-color: #ffffff;
    margin: 0 28rpx 20rpx;
    padding: 32rpx;
    border-radius: 10rpx;

    .basicInfo {
      .petInfoBox {
        display: flex;
        align-items: center;

        .leftPetImg {
          width: 300rpx;
          height: 402rpx;
          border-radius: 16rpx;

          image {
            width: 100%;
            height: 100%;
          }
        }

        .rightBox {
          flex: 1;
          margin-left: 32rpx;
        }

        .title {
          font-weight: bold;
          font-size: 30rpx;
          color: #303030;
          line-height: 40rpx;
        }

        .editTextImg {
          width: 80rpx;
          height: 34rpx;
        }
      }
    }

    .diaryBox {
      .title1 {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 48rpx 0 16rpx;
        font-weight: bold;
        font-size: 30rpx;
        color: #303030;
        line-height: 40rpx;

        :nth-child(2) {
          background-color: #d9f700;
          padding: 0 40rpx;
          border-radius: 50rpx;
          height: 48rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24rpx;
        }
      }
    }

    .bodyData {
      .title1 {
        margin: 48rpx 0 16rpx;
        font-weight: bold;
        font-size: 30rpx;
        color: #303030;
        line-height: 40rpx;
      }

      .bodyData-box {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;

        .form-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: calc(50% - 20rpx);

          .form-label {
            font-weight: 500;
            font-size: 24rpx;
            color: #7f7f7f;
          }

          .form-value {
            font-weight: bold;
            font-size: 26rpx;
            color: #303030;
          }
        }
      }
    }

    .natureBox {
      .title1 {
        margin: 48rpx 0 16rpx;
        font-weight: bold;
        font-size: 30rpx;
        color: #303030;
        line-height: 40rpx;
      }

      .natureText {
        font-weight: bold;
        font-size: 26rpx;
        color: #303030;
        line-height: 38rpx;
        padding: 16rpx 0;
        border-top: 2rpx solid #f8f8f8;
        border-bottom: 2rpx solid #f8f8f8;
      }
    }

    .medicalRecord {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-top: 32rpx;

      .title {
        font-weight: bold;
        font-size: 30rpx;
        color: #303030;
        line-height: 40rpx;
      }

      .moreText {
        font-weight: 400;
        font-size: 24rpx;
        color: #c69c6d;
      }
    }
  }

  .mainBoxHide {
    background-color: #ffffff;
    margin: 0 28rpx 20rpx;
    height: 64rpx;
    border-radius: 10rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .addBtn {
    background-color: #d9f700;
    margin: 20rpx 28rpx 0;
    height: 64rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 10rpx;
  }

  .shopListMain {
    display: flex;
    justify-content: space-between;

    .leftList {
      width: 49%;
    }

    .rightList {
      width: 49%;
    }

    .moreText {
      font-weight: 400;
      font-size: 24rpx;
      color: #c69c6d;
      margin: 60rpx auto 0;
      text-align: center;
    }

    .card {
      width: 100%;
      margin-bottom: 14rpx;
      background-color: #fff;
      border-radius: 10rpx;
      overflow: hidden;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      position: relative;
      overflow: hidden;
    }

    .image-container {
      overflow: hidden;
      position: relative;
      width: 100%;

      .image {
        width: 100%;
        height: auto;
        display: block;
      }
    }

    .video-container {
      overflow: hidden;
      position: relative;
      width: 100%;

      .image {
        width: 100%;
        height: 100%;
        display: block;
        object-fit: cover;
      }
    }

    .bofangImg {
      width: 32rpx;
      height: 32rpx;
      position: absolute;
      top: 16rpx;
      right: 16rpx;
    }

    .DirartText {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 16rpx 26rpx 24rpx;
      background-color: rgba(0, 0, 0, 0.35);
      font-weight: bold;
      font-size: 24rpx;
      color: #ffffff;
    }
  }
}
</style>
